import { message } from 'antd';

import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';

import { useNavigate, useLocation } from 'react-router-dom';
import { useContextSelector } from 'use-context-selector';
import MessageList from '@/pages/app-qa/components/chat/components/MessageList';
import chatService from '@/api/services/chatService';

import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import timezone from 'dayjs/plugin/timezone';
dayjs.extend(utc);
dayjs.extend(timezone);

import useWindowWidth from '@/hooks/event/use-window-width';
import { logout } from '@/pages/auth/authUtils';
import { useParams } from '@/router/hooks';

import ChatBox from './components/ChatBox';
import ChatContextProvider, { ChatContext } from './context';
import './styles/chat.css';
import { Quote, StartChatFnProps, ToolModuleResponseItemType } from './tools/constants';

import { useDatasetPermit } from '@/store/configStore';

import { useConfigActions, useInitializeData } from '@/store/configStore';

import { useChatActions } from '@/store/chatStore';

import { useOrchestrationStore } from '@/store/orchestrationStore';
import { useUserInfo, useUserState } from '@/store/userStore';
import { StreamResponseType } from './tools/fetch';
import { AppWorkbenchType } from '@/common/app/constants';
import orchestrationService from '@/api/services/orchestrationService';

import styles from '../homepage2/index.module.scss';
import FusionAppList from '../homepage2/components/FusionAppList';
import { SvgIcon } from '@/components/icon';
import GreenScreenVideo from '@/components/digital-human/green-screen-video';
import DigitalHuman from '@/components/digital-human';
// import DigitalHuman from '@/components/digital-human/index2';
import { useMetahumanStore } from '@/store/metahumanStore';


interface Message {
  text: string;
  isUser: boolean;
  loading?: boolean;
  loadingText?: string;
  chatId?: string;
  dataId?: string;
  ts?: number;
  quote?: Quote[];
  toolJson?: Record<string, any>;
  interactive?: any;
  params?: any;
  userGoodFeedback?: string;
  userBadFeedback?: string;
  appName?: string;
  appLogo?: string;
  appType?: string;
  appId?: string;
  shareId?: string;
}

interface ChatProps {
  initialMessage?: string;
  chatId?: string;
  onStartChat?: (e: StartChatFnProps) => Promise<
    StreamResponseType & {
      isNewChat?: boolean;
    }
  >;
  onUpdateHistory?: () => void;
  workflowDebug?: boolean;
  isAuthority?: boolean;
}

function Chat({
  initialMessage,
  chatId,
  isAuthority = true,
  onStartChat,
  onUpdateHistory,
  workflowDebug = false,
}: ChatProps) {
  const {
    virtualAvatarEnabled,
    isConnected,
    stopSpeaking,
  } = useMetahumanStore();
  
  const initializeData = useInitializeData();
  const { fetchInitialInfo } = useConfigActions();

  const { isPc } = useWindowWidth();

  const datasetPermit = useDatasetPermit();

  const [messageApi, contextHolder] = message.useMessage();
  const [historyMessages, setHistoryMessages] = useState<Message[]>([]);
  const [initChatId, setInitChatId] = useState('');
  const [isDigitalHumanConnected, setIsDigitalHumanConnected] = useState(false);
  const [digitalHumanVideoStream, setDigitalHumanVideoStream] = useState<MediaStream | null>(null);
  const { chatId:currentChatId } = useParams() as { chatId: string };

  const location = useLocation();

  // 初始化消息或处理聊天记录
  useEffect(() => {
    if (chatId) {
      // 如果提供了chatId，加载聊天记录
      handleChatRecords(chatId);
    }
  }, [initialMessage, chatId]);

    // 组件卸载时清理资源
  useEffect(() => {
    return () => {
      console.log('组件卸载，清理资源', virtualAvatarEnabled, isConnected, chatId, currentChatId);
      virtualAvatarEnabled && isConnected && stopSpeaking(currentChatId);
    }
  }, []);

  const searchParams = new URLSearchParams(location.search);
  const id = searchParams.get('id') || searchParams.get('appId') || '';
  const sid = searchParams.get('sid') || searchParams.get('shareId') || '';
  // const [appType, setAppType] = useState('');

  const { setChatRecordLoading } = useConfigActions();

  const { setSearchQuestion } = useChatActions();

  const { t } = useTranslation();

  const { isInOrchestrationPage, appDetail, fusionAppId } = useOrchestrationStore();

  // const fetchAppInfo = async () => {
  //   const appDetailInfo = await orchestrationService.getAppDetailV2(id, AppWorkbenchType.public);
  //   setAppType(appDetailInfo?.appType || '');
  // }

  // useEffect(() => {
  //   setAppType(appDetail?.appType || '');
  // }, [appDetail])

  // useEffect(() => {
  //   if (id && !appDetail) {
  //     fetchAppInfo();
  //   }
  // }, [id]);

  useEffect(() => {
    console.log(id, sid);
    setSearchQuestion('');

    if (!id || Object.keys(initializeData).length === 0) {
      fetchInitialInfo();
    }
    return () => {};
  }, []);

  const handleChatRecords = async (selectChatId: string) => {
    if (!id || !selectChatId) return;

    let datasetPermitList = datasetPermit;

    let appType = appDetail?.appType;
    if (!appType) {
      const appDetailInfo = await orchestrationService.getAppDetailV2(id, AppWorkbenchType.public);
      appType = appDetailInfo?.appType;
    }

    setChatRecordLoading(true);
    try {
      const resp = await chatService.ChatRecords({
        appId: id,
        chatId: selectChatId,
        pageSize: 1000,
      });

      const data = resp?.list || [];
      setInitChatId(selectChatId);

      // const msg: Message[] = data.map((item: any) => {
      //   const textContent = item.value
      //     .filter((i: any) => i?.type == 'text')
      //     .map((i: any) => i?.text?.content)
      //     .join('\n');

      //   const quoteList =
      //     datasetPermitList?.length > 0
      //       ? item?.totalQuoteList?.filter((i: any) => datasetPermitList.includes(i?.datasetId)) ||
      //         []
      //       : item?.totalQuoteList || [];

      //   const isUser = item.obj === 'Human';

      //   return {
      //     text: textContent,
      //     isUser: isUser,
      //     chatId: selectChatId,
      //     dataId: item?.dataId,
      //     quote: quoteList,
      //     userGoodFeedback: item?.userGoodFeedback || '',
      //     userBadFeedback: item?.userBadFeedback || '',
      //   };
      // });

      const msg: Message[] = data.map((item: any) => {
        let textContent = '';
        let toolJson: Record<string, ToolModuleResponseItemType> = {};
        let interactive = {};

        if (item.value && Array.isArray(item.value)) {
          item.value.forEach((valueItem: any) => {
            if (valueItem?.type === 'tool') {
              if (valueItem.tools?.length > 0) {
                valueItem.tools.forEach((toolData: any) => {
                  if (toolData?.id) {
                    textContent += `__TOOL_CALL_${toolData.id}__\n`;
                    toolJson[toolData.id] = {
                      id: toolData.id,
                      toolName: toolData.toolName || '',
                      toolAvatar: toolData.toolAvatar || '',
                      functionName: toolData.functionName || '',
                      params: toolData.new_args || toolData.params || '',
                      response: toolData.response || '',
                    };
                  }
                });
              }
            } else if (valueItem?.type === 'interactive') {
              interactive = valueItem?.interactive;
            } else if (valueItem?.type === 'text' && valueItem?.text?.content) {
              textContent += valueItem.text.content + '\n';
            }
          });
        }

        const quoteList: Quote[] =
          datasetPermitList?.length > 0
            ? item?.totalQuoteList?.filter((i: any) => datasetPermitList.includes(i?.datasetId)) || []
            : item?.totalQuoteList || [];

        const isUser = item.obj === 'Human';

        return {
          text: textContent || '',
          isUser: isUser,
          chatId: selectChatId,
          dataId: item?.dataId,
          quote: quoteList,
          toolJson: toolJson,
          interactive: interactive,
          params: (interactive as any)?.params,
          userGoodFeedback: item?.userGoodFeedback || '',
          userBadFeedback: item?.userBadFeedback || '',
          appName: item?.appName || '',
          appLogo: item?.appLogo || '',
          // appType: item?.appType || ''
          appType: appType || '',
          appId: item?.appId || '',
          shareId: item?.shareId || '',
        };
      });

      setHistoryMessages(msg);
    } catch (error) {
      console.error('获取聊天记录失败', error);
      messageApi.error('获取聊天记录失败');
    } finally {
      setChatRecordLoading(false);
    }
  };

  const { isGuest } = useUserState();

  // 处理数字人连接状态变化
  const handleDigitalHumanConnectionChange = (isConnected: boolean, videoStream?: MediaStream) => {
    setIsDigitalHumanConnected(isConnected);
    setDigitalHumanVideoStream(videoStream || null);
  };

  return (
    <div className={`chat-layout flex h-full w-full ${isPc ? '' : 'p-2'}`}>
      {contextHolder}
      <div
        // className="flex flex-col"
        className={isPc ? styles['homepage2-container'] : ''}
        style={{
          width: '100%',
          zIndex: 20
        }}
      >
        {/* {isPc && location?.pathname?.includes('fusion') && (
          <FusionAppList
            className="mt-6"
          />
        )} */}
        {location?.pathname?.includes('fusion') && isPc && <FusionAppList className="mt-6" />}
        {isPc && (
          <>
            <div className={`${styles['gradient-left']}`} />
          </>
        )}
        {isPc && (
          <>
            <div className={`${styles['gradient-right']}`} />
          </>
        )}
        {/* {!isPc && (
          <>
            <div className="pointer-events-none absolute left-0 top-0 z-0">
              <SvgIcon icon="mobile-chat-bg-left" size={375} />
            </div>
            <div className="pointer-events-none absolute -top-14 right-0 z-0">
              <SvgIcon icon="mobile-chat-bg-right" size={375} />
            </div>
          </>
        )} */}
        <div
          className="flex h-full"
          style={{
            display: 'flex',
            height: workflowDebug
              ? 'calc(100vh - 260px)'
              : isPc
                ? isInOrchestrationPage
                  ? 'calc(100vh - 130px)'
                  : 'calc(100vh - 60px)'
                : 'calc(100vh - 60px)',
            // height: workflowDebug
            //   ? 'calc(100vh - 260px)'
            //   : isPc
            //     ? isGuest
            //       ? 'calc(100vh - 80px)'
            //       : isInOrchestrationPage
            //         ? 'calc(100vh - 150px)'
            //         : 'calc(100vh - 80px)'
            //     : 'calc(100vh - 60px)',
              // fusionAppId
              // ? 'calc(100vh - 120px)'
              // : 'calc(100vh - 60px)',
            gap: '0',
            padding: isPc ? '0 20px 20px 20px' : '0px',
          }}
        >
          {isAuthority ? (
            <ChatBox
              initialMessages={historyMessages}
              initialQuestion={initialMessage}
              initChatId={initChatId}
              isTest={false}
              onStartChat={onStartChat}
              workflowDebug={workflowDebug}
              onUpdateHistory={onUpdateHistory}
            />
          ) : (
            <MessageList messages={historyMessages} isChat={false} />
          )}
          {/* {isPc && virtualAvatarEnabled && (
            <div style={{ width: '400px', marginLeft: '20px' }}>
              <DigitalHuman
                avatarId={'metahuman_women'}
                appId={id}
              />
            </div>
          )} */}
        </div>
      </div>
    </div>
  );
}

function Render({
  initialMessage,
  chatId,
  isAuthority,
  onStartChat,
  onUpdateHistory,
  workflowDebug = false,
}: ChatProps) {
  return (
    <ChatContextProvider>
      <Chat
        initialMessage={initialMessage}
        chatId={chatId}
        isAuthority={isAuthority}
        onStartChat={onStartChat}
        onUpdateHistory={onUpdateHistory}
        workflowDebug={workflowDebug}
      />
    </ChatContextProvider>
  );
}

export default Render;
